﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;
using System.Threading;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 购买保险   (要返回购买成功还是购买失败用户客户端提示)
	/// </summary>
	public class Action30026 : BaseAction
	{
		private int tableId;
		private int userId;
		private int poolId;
		/// <summary>
		/// 购买的保险数量   这个是实际玩家支付的
		/// </summary>
		private int insuranceNum;
		/// <summary>
		/// 购买的保险outs牌  List<int>
		/// </summary>
		private string outsStr;
		private TableData _currentTable;
		private GameUser _currentGameUser;
		private List<int> tempOuts;

		private bool result = false;
		private string log = "";

		public Action30026(HttpGet actionGetter)
			: base((short)ActionType.DZBuyInsurance, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&
				httpGet.GetInt("UserId", ref userId) &&
				httpGet.GetInt("PoolId", ref poolId) &&
				httpGet.GetInt("BuyInsuranceNum", ref insuranceNum) &&
				httpGet.GetString("Outs", ref outsStr))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30026获得房间不存在");
				return false;
			}

			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				Tool.WriteWarmingLine("消息30026玩家不存在");
				return false;
			}
			if (_currentTable.State != TableState.Insurance)
			{
				Tool.WriteWarmingLine("消息30026  当前房间不是保险状态");
				return false;
			}
			if(insuranceNum <= 0)
			{
				Tool.WriteErrorLine("消息 30026 没有花钱购买保险");
				return false;
			}
			
			try
			{
				tempOuts = ProtoBufUtils.Deserialize<List<int>>(Convert.FromBase64String(outsStr));
				if (tempOuts == null)
				{
					Tool.WriteErrorLine("消息30026解包错误");
					return false;
				}
				if (tempOuts.Count <= 0)
				{
					Tool.WriteErrorLine("消息30026提交的牌数量为0，不符合要求");
					return false;
				}
				
				

				SimpleInsuranceModelPool tempPool = null;
				foreach (var pool in _currentTable.InsurancePool)
				{
					if (pool.NumberID == poolId)
					{
						tempPool = pool;
						break;
					}
				}
				if(tempPool == null)
				{
					result = false;
					log = "保险底池不存在";
				}
				else
				{
					//校验提交的outs的合法性
					foreach(var card in tempOuts)
					{
						if(!tempPool.Outs.Contains(card))
						{
							result = false;
							log = "当期提交的保险outs有误";
							return false;
						}
					}
					var outsList = new ShareCacheStruct<OutsOddsInfo>().FindAll();
					OutsOddsInfo odds = outsList.Where(i => i.Outs == tempOuts.Count).First();
					if(odds == null)
					{
						odds = outsList.Max();
					}

					//购买的筹码的合法性判断
					//当前购买的筹码 不能大于可购买的最大值
					int maxCanBuy = _currentTable.MaxCanBuyChipNum(tempPool.AntNum, userId);
					var maxCost = (int)Math.Floor(maxCanBuy / odds.Odds);
					if(insuranceNum > maxCost)
					{
						//提交的金额不合法
						Tool.WriteErrorLine("提交的购买的金额不合法");
						return false;
					}

					tempPool.CurrentRoundIsOperated = true;
					tempPool.ActualBuyNum = insuranceNum;
					_currentTable.AddUserBuyInsuranceActually(userId, insuranceNum);
					tempPool.BuyOuts.Clear();
					tempPool.BuyOuts.AddRange(tempOuts);
					tempPool.IsBuyInsurance = true;
					
					odds = outsList.Where(i => i.Outs == tempOuts.Count).First();
					tempPool.ActualOdds = odds.Odds;
					tempPool.CurrentRoundCompensate = (int)Math.Floor(insuranceNum * odds.Odds);
					_currentTable.AddInsuranceBuyCount(userId, tempPool.CurrentRoundCompensate);
				}
			}

			catch (Exception ex)
			{
				Tool.WriteErrorLine(string.Format("消息30026异常:{0}", ex.ToString()));
				return false;
			}

			Tool.WriteErrorLine("Action 30027 广播玩家购买保险");
			var parameters = new Parameters();
			parameters["TableID"] = tableId;
			parameters["UserID"] = userId;
			parameters["OutsNum"] = tempOuts.Count;
			GameTable.Current.SyncNotifyAction((int)ActionType.DZBrocastBuyInsurance, _currentTable, parameters, t =>
			{
				Console.WriteLine("Action 30027 广播玩家购买保险");
			});

			result = true;
			return true;
		}

		public void ThreadFunc()
		{
			Tool.WriteErrorLine("回合结束操作，延时0.5s");
			System.Threading.Thread.Sleep(500);

			GameTable.Current.RoundInsuranceOperate(_currentTable);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.tableId);
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.log);
			//开启新的线程来避免阻塞
			Thread t1 = new Thread(new ThreadStart(ThreadFunc));
			t1.IsBackground = true;
			t1.Start();
		}
	}
}
